import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getSid,getToken } from '@/utils/auth'
import urlparam from "@/api/ps_form.js"
import qs from 'qs'
import _ from 'lodash'
import router from '../router'
// create an axios instance
axios.defaults.withCredentials = true;
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  withCredentials: true, // send cookies when cross-domain requests
  //headers:{'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
  timeout: 50000 // request  meout

})
function getRandom(){
  return new Date().getTime()+((1+Math.random())*1000).toFixed("2")+"";
}
// request interceptor
service.interceptors.request.use(
  config => {
    if(config.voParam){
      let objs=["number","string","undefined","boolean","object"];
        let voParam=config.voParam;
        let _param={};
        for(let s in voParam){
          if(objs.indexOf(typeof s) && !_.isEmpty(voParam[s])){
            _param['vo.string('+s+")"]=voParam[s];
          }
        }
        config.data=config.data||{};
        _.extend(config.data,_param);

    }
    // do something before request is sent
    if(config.method=='post'||config.method=="POST"){
      config.data = qs.stringify(config.data)
      config.headers=config.headers||{"Content-type":"application/x-www-form-urlencoded;charset=utf-8"}
    }
    let url=urlparam.realUrl(config.url,config.urlparam);
     if(config.notNeedToken){

     }else if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      let token=getToken();
      if(_.isEmpty(token)){
        store.dispatch("user/resetToken")
        store.dispatch('tagsView/delAllViews', null, { root: true })
        router.push("/login")
        return Promise.reject();
        return;
      }
      let sid=getSid();
       if(url.indexOf("token")==-1){
         url+=(url.indexOf("?")==-1?"?":"&")+"token="+token+"&_SID="+sid;
       }
       if(url.indexOf("_VIEWER")==-1)
       url+='&_VIEWER=APP';
       if(url.indexOf("_PID")==-1){
        url+=(url.indexOf("?")==-1?"?":"&")+"_PID="+getRandom()
      }
      //  if(!config. headers){
      //   config.headers= {
      //   'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
      //   }
      //  }
       config.url=url;
       // config.headers["uuid"]=token;
      //config.headers['x-token'] = token
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data

    if(response.status ==200){
      //console.log(config.url,response)
      if(res.result=='LOGON' && res.errorCode=='-5'){
        store.dispatch("user/resetToken")
        store.dispatch('tagsView/delAllViews', null, { root: true })
        router.push("/login")
        return Promise.reject();
      }
      let token=res.token,sid=res._SID;
      if(token && sid)
       store.dispatch("user/setUserToken",{token:token,_SID:sid})
      if(res.tokenerror && res.tokenerror=="notoken"){
        store.dispatch("user/resetToken")
        return Promise.reject();
      }
      if(typeof res=='string'){
        try{
         return eval(`(${res})`)
        }catch(e){
          return res;
        }
      }
      return res;
    }
    Message({
      message: " 发生错误,"+response.status+" ",
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(new Error(res.message || 'Error'))
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service

